/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utilities;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.*;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.w3c.dom.*;
import org.xml.sax.*;

/**
 * @author Tung An
 */
public class XMLUtilities {

    public static Node parseDom(String xml) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        Document doc = db.parse(is);
        return doc;
    }

    public static String saveImage(FileItem item, String path) throws IOException {
        String fileName = item.getName();
        String extension = "";

        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1);
        }
        InputStream content = item.getInputStream();
        BufferedImage bi = ImageIO.read(content);
        File outputfile = new File(path, fileName);
        ImageIO.write(bi, extension, outputfile);
        return fileName;
    }

    public static String saveImageFromURL(String url, String path) throws IOException {
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
        InputStream content = new BufferedInputStream(new URL(url).openStream());
        BufferedImage bi = ImageIO.read(content);
        File outputfile = new File(path, fileName);
        ImageIO.write(bi, extension, outputfile);
        return fileName;
    }

    public static StringWriter marshallObj(Object obj) {
        if (obj == null) return null;
        StringWriter xmlWriter = new StringWriter();
        try {
            JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.marshal(obj, xmlWriter);
        } catch (JAXBException ex) {
            Logger.getLogger(XMLUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
        return xmlWriter;
    }
}
